//
//  MNDInvestListViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/15.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDInvestListViewController.h"
#import "MNDMyInviteCell.h"
#import "SYRefreshControl.h"
#import "MNDInvestCountModel.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "WeiboSDK.h"
#import "MNDShareModel.h"
#import "MNDShareWebViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDInvestTipsViewController.h"
#import "MNDInvestDetailViewController.h"
#import "MNDInviteAlertViewController.h"
#import "MNDAwardRulesAlertViewController.h"
#import "UIButton+JKImagePosition.h"
#import "UIImageView+JKAddition.h"
#import "MNDInviteFriendListViewController.h"


@interface MNDInvestListViewController ()<UITableViewDelegate,UITableViewDataSource>
//tabview
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)  SYRefreshControl *syRefresh;
//@property (nonatomic, assign) NSInteger 

@property(assign,nonatomic) NSInteger pageNum;

//累计奖励
@property (weak, nonatomic) IBOutlet UILabel *incomeMoneyLabel;
//邀请人数
@property (weak, nonatomic) IBOutlet UILabel *inviteTotalLabel;
//昨日奖励
@property (weak, nonatomic) IBOutlet UILabel *yesterdayIncomeMoneyLabel;
//推荐码
@property (weak, nonatomic) IBOutlet UILabel *inviteCodeLabel;

@property(nonatomic, strong) MNDInvestCountModel *inviteModel;
@property (weak, nonatomic) IBOutlet UIButton *newestButton;


@end

@implementation MNDInvestListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的邀请";
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.newestButton jk_setImagePosition:LXMImagePositionRight spacing:4];
    [self loadInvestCount];
    [self initialBarbuttonItems];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(![MNDLoginUserModel isUserLogin]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"奖励规则" style:UIBarButtonItemStylePlain target:self action:@selector(awardRulesAction:)];
    
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

//温馨提示
- (IBAction)tipAction:(UIButton *)sender {
    MNDAwardRulesAlertViewController *rulesAlertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDAwardRulesAlertViewController"];
    rulesAlertVC.titleStr = @"温馨提示";
    rulesAlertVC.tipStr = self.inviteModel.reward_tip;
    [KeyWindow addSubview:rulesAlertVC.view];
    [self addChildViewController:rulesAlertVC];
}



- (void)loadEncodeUserCode {
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    
    [APIManager sendRequestWithPath:API_ENCODE_USERCODE parameters:[MNDSign signedParamWithDict:@{@"user_code": user.user_code}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                MNDInviteAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDInviteAlertViewController"];
                alertVC.inviteModel = self.inviteModel;
                [KeyWindow addSubview:alertVC.view];
                [weakself addChildViewController:alertVC];
                
                [alertVC.cancelButton bk_addEventHandler:^(id sender) {
                    [alertVC.view removeFromSuperview];
                    [alertVC removeFromParentViewController];
                } forControlEvents:UIControlEventTouchUpInside];
                
            });
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}


#pragma mark -加载数据
//邀请统计数据
- (void)loadInvestCount {
    
    kdeclare_weakself;
    [APIManager sendRequestWithPath:API_NEW_MY_INVITE parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakSelf.inviteModel = [MNDInvestCountModel mj_objectWithKeyValues:responseModel.data];
            [self configContents];
            [weakSelf.tableView reloadData];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContents {
    self.incomeMoneyLabel.text = self.inviteModel.all_reward;
    self.inviteTotalLabel.text = self.inviteModel.invite_tender_money;
    self.yesterdayIncomeMoneyLabel.text = self.inviteModel.reward_new;
    self.inviteCodeLabel.text = [NSString stringWithFormat:@"专属推荐码：%@",self.inviteModel.invite_code];
}

#pragma mark - 分享
- (void)shareWithContents: (MNDShareModel *)content {
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText: content.share_txt
                                     images: content.share_img
                                        url: [NSURL URLWithString:content.share_url]
                                      title: content.share_title
                                       type: SSDKContentTypeWebPage];
    
    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:content.share_url]
                                  thumbImage: nil
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatSession];
    
    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:content.share_url]
                                  thumbImage: nil
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatTimeline];
    
    [shareParams SSDKSetupQQParamsByText: content.share_txt
                                   title: content.share_title
                                     url: [NSURL URLWithString:content.share_url]
                              thumbImage: nil
                                   image: content.share_img
                                    type: SSDKContentTypeWebPage
                      forPlatformSubType: SSDKPlatformTypeQQ];
    
    //微博分享内容
    [shareParams SSDKSetupSinaWeiboShareParamsByText: content.share_txt
                                               title: content.share_title
                                              images: content.share_img
                                               video: nil
                                                 url: [NSURL URLWithString:content.share_url]
                                            latitude: 0
                                           longitude: 0
                                            objectID: nil
                                      isShareToStory: NO
                                                type: SSDKContentTypeAuto];
    
    //使用客户端分享
    [shareParams SSDKEnableUseClientShare];
    
    NSMutableArray *items = [NSMutableArray arrayWithArray:@[@(SSDKPlatformSubTypeWechatSession),
                                                             @(SSDKPlatformSubTypeWechatTimeline),
                                                             @(SSDKPlatformSubTypeQQFriend),
                                                             @(SSDKPlatformTypeSinaWeibo)]];
    
    //调用分享的方法
    [ShareSDK showShareActionSheet:self.view
                       customItems:items
                       shareParams:shareParams
                sheetConfiguration:nil
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        
                        switch (state) {
                            case SSDKResponseStateBegin:
                            {
                                
                                NSLog(@"分享开始");
                            }
                                break;
                            case SSDKResponseStateSuccess:
                            {
                                NSLog(@"分享成功!");
                                [NetworkProgressHUD showHudMsg:@"分享成功"];
                            }
                                
                                break;
                            case SSDKResponseStateFail:
                            {
                                NSLog(@"分享失败%@",error);
                                
                                NSString *message = [NSString stringWithFormat:@"分享失败:%@", error.userInfo[@"error_message"]];
                                if (![WeiboSDK isWeiboAppInstalled]) {
                                    message = @"您未安装微博客户端, 无法分享";
                                }
                                
                                [NetworkProgressHUD showHudMsg: message];
                            }
                                break;
                            case SSDKResponseStateCancel:
                            {
                                // [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
                                //MBProgressHUD *HUD = [MBProgressHUD HUDForView:weakSelf.view];
                                // HUD.labelText = @"已取消分享";
                                //HUD.mode = MBProgressHUDModeText;
                                //[HUD hide:YES afterDelay:1.5];
                                NSLog(@"分享已取消");
                            }
                                break;
                            default:
                                break;
                        }
    }];
    //删除和添加平台示例
    //(默认微信，QQ，QQ空间都是直接跳客户端分享，加了这个方法之后，可以跳分享编辑界面分享)
    //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
    //（加了这个方法之后可以不跳分享编辑界面，直接点击分享菜单里的选项，直接分享）
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
}


#pragma mark -UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MNDMyInviteCell *investListCell = [tableView dequeueReusableCellWithIdentifier:@"MNDMyInviteCell"];
    if (indexPath.row == 0) {
        investListCell.titleLabel.hidden = NO;
        investListCell.totalTipLabel.hidden = NO;
        investListCell.totalMoneyLabel.hidden = NO;
        investListCell.titleLabel.text = @"撮合奖励";
        investListCell.subtitleLabel.text = @"最新撮合奖励:";
        if (self.inviteModel) {
            investListCell.yesterdayEarnMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.inviteModel.make_reward_new];
            investListCell.totalMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.inviteModel.make_reward];
        }
        
    }else if(indexPath.row == 1){
        investListCell.titleLabel.hidden = NO;
        investListCell.totalTipLabel.hidden = NO;
        investListCell.totalMoneyLabel.hidden = NO;
        investListCell.titleLabel.text = @"邀请奖励";
        investListCell.subtitleLabel.text = @"最新邀请奖励:";
        if (self.inviteModel) {
            investListCell.yesterdayEarnMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.inviteModel.redpack_reward_new];
            investListCell.totalMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.inviteModel.redpack_reward];
        }
        
    }else{
        static NSString *const cellIdentifier = @"cell1";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if (!cell) {
    
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView *accesoryView = [UIImageView jk_imageViewWithImageNamed:@"right_arrow"];
        cell.accessoryView = accesoryView;
        cell.textLabel.text = [NSString stringWithFormat:@"好友邀请人数:%@人",self.inviteModel.invite_num ? self.inviteModel.invite_num : @"0"];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0];
        cell.textLabel.textColor = [UIColor blackColor];
        return cell;
    }
    return investListCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row != 2) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
        MNDInvestDetailViewController * listVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestDetailViewController"];
        listVC.index = indexPath.row+1;
        [self.navigationController pushViewController:listVC animated:YES];
    }else {
        MNDInviteFriendListViewController *friendListVC = [UIStoryboard viewControllerWithIdentifier:@"MNDInviteFriendListViewController"];
        [self.navigationController pushViewController:friendListVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 71;
}

//奖励规则
-(void)awardRulesAction:(id)sender {
    MNDAwardRulesAlertViewController *rulesAlertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDAwardRulesAlertViewController"];
    rulesAlertVC.tipStr = self.inviteModel.invite_reward_rule;
    [KeyWindow addSubview:rulesAlertVC.view];
    [self addChildViewController:rulesAlertVC];
}


//立即邀请
- (IBAction)shareAction:(UIButton *)sender {
    if (self.isFromInvitePage) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self loadEncodeUserCode];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
